package com.supplychainapi.controller;

import com.joindata.inf.common.basic.exceptions.ServiceException;
import com.supplychainapi.common.ApiVersion;
import com.supplychainapi.common.BizCode;
import com.supplychainapi.common.RestResponse;
import com.supplychainapi.common.enums.ExceptionMessage;
import com.supplychainapi.config.FastdfsConfig;
import com.supplychainapi.domain.LoginCache;
import com.supplychainapi.fastdfs.BuildFastDfs;
import com.supplychainapi.fastdfs.FastDfsClient;
import com.supplychainapi.param.TbmaterialParam;
import com.supplychainapi.service.*;
import com.supplychainapi.utils.Constants;
import com.supplychainapi.utils.PathUitls;
import com.supplychainapi.utils.StringUtil;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ExecutionException;

/**
 * 物料
 *
 * @Time 2017年9月25日
 * @author wangziqi
 */
@RequestMapping(PathUitls.ROOT_PHONE+"/{version}/materials")
@RestController
@Api(value = "MaterialsController", description = "物料crud")
public class MaterialsController extends BaseController {

	private Logger logger = LogManager.getLogger(this.getClass());

	@Autowired
	private TbMaterialService materialService;

	@Autowired
	TbSeqNoService seqNoService;

	@Autowired
	IScmTbtreebuildService tbtreebuildService;


	@Autowired
	IScmTbstorageService tbstoragePhoneService;


	@Autowired
	ITbfinderlistService tbfinderlistService;


	@Autowired
	BuildFastDfs buildFastDfs;

	@PostConstruct
	public FastDfsClient getFastDfsClient(){

		this.fastDfsClient=buildFastDfs.buildClient();
		return fastDfsClient;
	}

	private FastDfsClient fastDfsClient;


	@Autowired
	FastdfsConfig fastdfsConfig;


	/**
	 * 新增物料
	 *
	 */
	@ApiVersion(1)
	@ApiOperation(value="新增物料", notes="方便测试使用swagger测试")
	@RequestMapping(value = "/save", method=RequestMethod.POST)
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="query", name = "fsMaterialId", value = "物料代码;swagger", required = true, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType="query", name = "fsMaterialName", value = "物料名称;swagger", required = true, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType="query", name = "fsNodeCode", value = "物料分类;swagger", required = true, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType="query", name = "fsModelno", value = "规格型号;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType="query", name = "fsUnitId", value = "基本单位;swagger", required = true, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType="query", name = "fsImgUrl", value = "物料图片;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType="query", name = "fsSupplierId", value = "首选供应商;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType="query", name = "fdOrderPrice", value = "采购单价;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType="query", name = "fdSalePrice", value = "销售单价;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType="query", name = "fdIncomeRate", value = "进项税率;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType="query", name = "fdOutputRate", value = "销项税率;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType="query", name = "fiShelve", value = "上下架;swagger", required = false, dataType = "String", defaultValue = "1"),
			@ApiImplicitParam(paramType="query", name = "fsStorageId", value = "默认仓库;swagger", required = false, dataType = "String", defaultValue = ""),
	})
	public RestResponse save(@ApiIgnore LoginCache loginCache,@ApiIgnore @RequestBody TbmaterialParam model) throws ServiceException{
//		String shopGuid=request.getParameter("shopGuid");
		model.setFsCreateTime(new Date());
		model.setFsCreateUserId(loginCache.getFsUserId());
		model.setFsCreateUserName(loginCache.getFsUserName());
		model.setFsShopGUID(loginCache.getFsShopGUID());
		return materialService.save(model);
	}

	public static void main(String[] args) throws ClassNotFoundException {
		System.out.println(StringUtil.getClassName(Class.forName("com.supplychainapi.controller.MaterialsController")));
		System.out.println(StringUtil.getMethodName());
	}

	@ApiVersion(1)
	@ApiOperation(value="删除物料", notes="")
	@RequestMapping(value = "/delete", method=RequestMethod.GET)
	public RestResponse delete(@ApiIgnore LoginCache loginCache,@ApiParam(value = "物料id") @RequestParam String id) throws ServiceException{

		return materialService.delete(new TbmaterialParam(id,loginCache.getFsShopGUID()));
	}

	@ApiVersion(1)
	@ApiOperation(value="查询", notes="")
	@RequestMapping(value = "/select", method=RequestMethod.GET)
	public RestResponse select(@ApiIgnore LoginCache loginCache,@ApiParam("主键id") @RequestParam String id) throws ServiceException{

		return materialService.selectById(loginCache.getFsShopGUID(),id);
	}

//	@ApiVersion(1)
//	@ApiOperation(value="查询", notes="")
//	@RequestMapping(value = "/selectAll", method=RequestMethod.GET)
//	public RestResponse selectAll(@ApiIgnore LoginCache loginCache) throws ServiceException{
//
//		return materialService.selectAll(loginCache.getFsShopGUID());
//	}

	@ApiVersion(1)
	@ApiOperation(value="查询物料分类", notes="")
	@RequestMapping(value = "/getMaterialClass", method=RequestMethod.GET)
	public RestResponse getMaterialClass(@ApiIgnore LoginCache loginCache, HttpServletRequest request, @ApiParam(value = "父节点编码", required = false) @RequestParam(required = false) String fdParentNodeCode, @ApiParam(value = "shopguid,不传默认登录的shopid", required = false) @RequestParam(required = false) String shopid) throws ServiceException {
//		String fdParentNodeCode=request.getParameter("fdParentNodeCode");
		if (StringUtils.isBlank(shopid)) {
			return RestResponse.success(tbtreebuildService.getScmTbtreebuildAllInfos(loginCache.getFsShopGUID(), Constants.MATERIAL_CLASS, fdParentNodeCode
			));
		} else {
            return RestResponse.success(tbtreebuildService.getScmTbtreebuildAllInfos(shopid, Constants.MATERIAL_CLASS, fdParentNodeCode));
        }
	}

//	@ApiVersion(1)
//@Deprecated
//	@ApiOperation(value="查询物料仓库", notes="")
//	@RequestMapping(value = "/getMaterialStore/{page}/{pageSize}", method=RequestMethod.GET)
//	public RestResponse getMaterialStore( @ApiIgnore LoginCache loginCache,HttpServletRequest request,@PathVariable Integer page,@PathVariable Integer pageSize) throws ServiceException {
//
//		return RestResponse.success(tbstoragePhoneService.getScmTbstorageListInfo(loginCache.getFsShopGUID(),page,pageSize));
//	}
//
//
//	@ApiVersion(1)
//	@Deprecated
//	@ApiOperation(value="查询物料供应商", notes="")
//	@RequestMapping(value = "/getMaterialSupplier", method=RequestMethod.GET)
//	public RestResponse getMaterialSupplier(@ApiIgnore LoginCache loginCache, HttpServletRequest request) throws ServiceException {
//
//		return RestResponse.success(tbtreebuildService.getScmTbtreebuildInfos(loginCache.getFsShopGUID()));
//	}

//	@ApiVersion(1)
//	@Deprecated
//	@ApiOperation(value="获取所有物料按分类", notes="")
//	@RequestMapping(value = "/getMaterialAll", method=RequestMethod.GET)
//	public RestResponse getMaterialAll(@ApiIgnore LoginCache loginCache,HttpServletRequest request) throws ServiceException {
//
//		return RestResponse.success(materialService.selectAll(loginCache.getFsShopGUID()));
//	}




	//获取自动编码接口
	@ApiVersion(1)
	@ApiOperation(value="上传照片", notes="")
	@RequestMapping(value = "/uploadImage", method=RequestMethod.POST)
	public RestResponse uploadImage(@ApiIgnore LoginCache loginCache,@RequestParam MultipartFile file) throws ServiceException, IOException, ExecutionException, InterruptedException {

		if (null != file) {
			//转换成多部分request
			long size = file.getSize();
 			if (Math.ceil(Math.ceil(size / 1024) / 1024) > 1) {//文件大于2m
				return RestResponse.fail(Integer.valueOf(BizCode.FILE_SERVICE_FAIL0.getCode()), "大于1m");
			}
			String path=fastDfsClient.upload(file.getBytes(),file.getOriginalFilename(),Constants.IMAGE_SAVE_PATH);
			return RestResponse.success(fastdfsConfig.getDomain().concat(path));
		}
		return RestResponse.fail(Integer.valueOf(BizCode.FILE_SERVICE_FAIL0.getCode()),"文件上传失败");
	}

	//获取自动编码接口
	@ApiVersion(1)
	@ApiOperation(value="搜索", notes="")
	@RequestMapping(value = "/search", method=RequestMethod.GET)
	public RestResponse search(@ApiIgnore LoginCache loginCache,@ApiParam("分页页码从1开始") @RequestParam Integer page,@ApiParam("每页条数") @RequestParam Integer size, @ApiParam("搜索关键字") @RequestParam String name) throws ServiceException, IOException, ExecutionException, InterruptedException {
		if (StringUtils.isBlank(name)) {
			throw ExceptionMessage.missing_param.getServiceException();
		}
		return materialService.search(loginCache.getFsShopGUID(), name,page,size);
	}



	@ApiVersion(1)
	@ApiOperation(value="获取所有物料分类 给至二级截止", notes="")
	@RequestMapping(value = "/getMaterialAllClass", method=RequestMethod.GET)
	public RestResponse getMaterialAllClass(@ApiIgnore LoginCache loginCache) throws ServiceException {
		return materialService.getMaterialAllClass(loginCache.getFsShopGUID());
	}


	@ApiVersion(1)
	@ApiOperation(value="根据一级分类获取所有物料", notes="")
	@RequestMapping(value = "/getMaterialByClass", method=RequestMethod.GET)
	public RestResponse getMaterialByClass(@ApiIgnore LoginCache loginCache,@ApiParam("分页页码从1开始") @RequestParam Integer page,@ApiParam("每页条数") @RequestParam Integer size,@ApiParam("分类代码") @RequestParam String fsNodeCode) throws ServiceException {
		return materialService.selectByClass(loginCache.getFsShopGUID(),fsNodeCode,page,size);
	}

	@ApiVersion(1)
	@ApiOperation(value="根据二级分类获取所有物料", notes="")
	@RequestMapping(value = "/getMaterialByTwoClass", method=RequestMethod.GET)
	public RestResponse getMaterialByTwoClass(@ApiIgnore LoginCache loginCache,@ApiParam("分类代码") @RequestParam String fsNodeCode) throws ServiceException {
		return materialService.selectByTwoClass(loginCache.getFsShopGUID(),fsNodeCode);
	}


	@ApiVersion(1)
	@ApiOperation(value="获取所有物料不区分分类", notes="")
	@RequestMapping(value = "/getAllMaterial", method=RequestMethod.GET)
	public RestResponse getAllMaterial(@ApiIgnore LoginCache loginCache,@ApiParam("页码") @RequestParam Integer page,@ApiParam("每页条数") @RequestParam Integer size) throws ServiceException {
		return materialService.getAllMaterial(loginCache.getFsShopGUID(),page,size);
	}

	@ApiVersion(1)
	@ApiOperation(value = "修改物料", notes = "")
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "fsMaterialId", value = "物料代码;swagger", required = true, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType = "query", name = "fsMaterialName", value = "物料名称;swagger", required = true, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType = "query", name = "fsNodeCode", value = "物料分类;swagger", required = true, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType = "query", name = "fsModelno", value = "规格型号;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType = "query", name = "fsUnitId", value = "基本单位;swagger", required = true, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType = "query", name = "fsImgUrl", value = "物料图片;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType = "query", name = "fsSupplierId", value = "首选供应商;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType = "query", name = "fdOrderPrice", value = "采购单价;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType = "query", name = "fdSalePrice", value = "销售单价;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType = "query", name = "fdIncomeRate", value = "进项税率;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType = "query", name = "fdOutputRate", value = "销项税率;swagger", required = false, dataType = "String", defaultValue = ""),
			@ApiImplicitParam(paramType = "query", name = "fiShelve", value = "上下架;swagger", required = false, dataType = "String", defaultValue = "1"),
			@ApiImplicitParam(paramType = "query", name = "fsStorageId", value = "默认仓库;swagger", required = false, dataType = "String", defaultValue = ""),
	})
	public RestResponse update(@ApiIgnore LoginCache loginCache, @ApiIgnore @RequestBody TbmaterialParam model) throws ServiceException {
//		String shopGuid=request.getParameter("shopGuid");
//		model.setFsShopGUID(shopGuid);
		model.setFsUpdateTime(new Date());
		model.setFsUpdateUserId(loginCache.getFsUserId());
		model.setFsUpdateUserName(loginCache.getFsUserName());
		model.setFsShopGUID(loginCache.getFsShopGUID());
		return materialService.update(model);

	}

	@ApiOperation(value="进项税率", notes="")
	@RequestMapping(value = "/rate", method=RequestMethod.GET)
	public RestResponse rate(@ApiIgnore LoginCache loginCache) throws ServiceException {
		return RestResponse.success(materialService.geTrate());

	}

}
